import service from '@/utils/request'
import qs from 'qs'

// 请求方法
const http = {
    post(url, params) {
        return service.post(url, params, {
            transformRequest: [(params) => {
                return JSON.stringify(params)
            }],
            headers: {
                'Content-Type': 'application/json'
            }
        })
    },

    put(url, params) {
        return service.put(url, params, {
            transformRequest: [(params) => {
                return JSON.stringify(params)
            }],
            headers: {
                'Content-Type': 'application/json'
            }
        })
    },

    // params => {id:10}
    // qs 参数序列化
    // http://localhost:8080/api/user?id=10
    get(url, params) {
        return service.get(url, {
            params: params,
            paramsSerializer: (params) => {
                return qs.stringify(params)
            }
        })
    },
    getRestApi(url, params) {
        let _params
        if (Object.isparams, undefined || null) {
            _params = ''
        } else {
            _params = '/'
            for (const key in params) {
                console.log(key)
                console.log(params[key])
                if (params.hasOwnProperty(key) && params[key] !== null && params[key] !== '') {
                    _params += `${params[key]}/`
                }
            }
            // 去掉参数最后一位？
            _params = _params.substr(0, _params.length - 1)
        }
        console.log(_params)
        if (_params) {
            return service.get(`${url}${_params}`)
        } else {
            return service.get(url)
        }
    },
    delete(url, params) {
        let _params
        if (Object.isparams, undefined || null) {
            _params = ''
        } else {
            _params = '/'
            for (const key in params) {
                console.log(key)
                console.log(params[key])
                if (params.hasOwnProperty(key) && params[key] !== null && params[key] !== '') {
                    _params += `${params[key]}/`
                }
            }
            // 去掉参数最后一位？
            _params = _params.substr(0, _params.length - 1)
        }
        console.log(_params)
        if (_params) {
            return service.delete(`${url}${_params}`).catch(err => {
                message.error(err.msg)
                return Promise.reject(err)
            })
        } else {
            return service.delete(url).catch(err => {
                message.error(err.msg)
                return Promise.reject(err)
            })
        }
    },
    upload(url, params) {
        return service.post(url, params, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        })
    },

}


export default http
